﻿// License: MS-PL
// Based heavily on demo code that is part of http://msdn.microsoft.com/en-us/magazine/dd419663.aspx .
// Has been modified to fit coding style of MachineQA project.

using System;
using System.Diagnostics;
using System.Windows.Input;

namespace MachineQA
{
    /// <summary>
    /// A command whose sole purpose is to 
    /// relay its functionality to other
    /// objects by invoking delegates. The
    /// default return value for the CanExecute
    /// method is 'true'.
    /// </summary>
    public class RelayCommand : ICommand
    {
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        /// <summary>
        /// Default value is true, if a CanExecute delegate was supplied during construction than
        /// the return result from that delegate is returned.
        /// </summary>
        /// <param name="parameter">The parameter to pass to the CanExecute delegate.</param>
        /// <returns>True if the command can execute false otherwise.</returns>
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        /// <summary>
        /// Event handler to handle when CanExecute value changes.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Executes the command with the specified parameter
        /// </summary>
        /// <param name="parameter">The value to pass to the command.</param>
        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}